<?php
/**
 * Description: 作业--速算
 * User: lizhen
 * Date: 16/10/20
 * Time: 11:24
 */

require_once __DIR__ . '/ProcessExerciseBase.class.php';

class SusuanSingleModule extends ProcessExerciseBase {
    /**
     * 设置作业类型
     */
    protected function setExerciseType() {
        $this->data['exercise_type'] = 31;
    }

    /**
     * 设置作业题目内容
     */
    protected function setExerciseQuestion() {
        parent::setExerciseQuestion();
    }

    /**
     * 设置作业记录的状态
     */
    protected function setSubmitStatus() {
        if (empty($this->submitArgs['done'])) {
            $this->submitExerciseRecord['status'] = 0; //未完成
        } else {
            if ($this->exerciseInfo->end_time > $this->now)
                $this->submitExerciseRecord['status'] = 1; //已完成
            else
                $this->submitExerciseRecord['status'] = 5; //过期完成
        }
    }


    /**
     * 设置提交权限
     */
    protected function setSubmitPriv() {
        parent::setSubmitPriv();
    }

    /**
     * 设置用户答案
     *
     */
    protected function setUserAnswer() {

        $summary = json_decode($this->userExerciseRecord->summary, true);

        $this->data['user_answer'] = [];
        for ($i = 1; $i <= 6; $i++) {
            $key = 'level_'.$i;
            if (isset($summary[$key])) {
                $this->data['user_answer'][$key] = [
                    'duration'      => (int)$summary[$key]['duration'],
                    'accuracy'      => round($summary[$key]['right']/$summary[$key]['total'], 3),
                    'avg_duration'  => round($summary[$key]['duration']/$summary[$key]['total']),
                    'finish'        => $summary[$key]['right'] == $summary[$key]['total']
                ];
            }
        }
    }

    /**
     * 校验参数
     *
     * @param array $args 参数
     * @return bool
     */
    public function validateArgs($args) {
        if (!empty($args['level']) && isset($args['right']) && !empty($args['total']) && isset($args['duration'])) {
            $this->submitArgs = $args;
            return true;
        }

        return false;
    }

    /**
     * 保存作业答题记录记
     */
    protected function saveQuestionRecordsAndSetSubmitSummary() {

        $key = 'level_'.$this->submitArgs['level'];
        if (!empty($this->userExerciseRecord)) {
            $summary = json_decode($this->userExerciseRecord->summary, true);
        } else {
            $summary = [];
        }

        //更新该级别速算的统计信息,只有在第一次做或正确率高于当前才会更新
        $update = false;
        if (!isset($summary[$key])) { //第一次做
            $update = true;
        } elseif ($summary[$key]['right']/$summary[$key]['total'] < $this->submitArgs['right']/$this->submitArgs['total']) { //正确率比已有的高
            $update = true;
        } elseif ($summary[$key]['right'] == $this->submitArgs['right'] && $summary[$key]['duration'] > $this->submitArgs['duration']) { //正确率相等,时间比已有的短
            $update = true;
        }

        if ($update) {
            $summary[$key] = [
                'right'     => $this->submitArgs['right'],
                'total'     => $this->submitArgs['total'],
                'duration'  => (int)$this->submitArgs['duration']
            ];
        }

        if ($this->submitArgs['right'] == $this->submitArgs['total']) {

            //记录是第几个完成作业的人
            if (!isset($summary[$key]['ranking'])) {
                $summary[$key]['ranking'] = VipUtils::getRanking($this->submitArgs) + 1;
                VipUtils::setRanking($this->submitArgs);
            }
            //最快纪录
            if (!isset($summary[$key]['fastest']) || $summary[$key]['fastest'] > $this->submitArgs['duration']) {

                //返回值格式
                $this->submitArgs['is_arr'] = 2;
                //作业类型
                $this->submitArgs['type_id'] = $this->exerciseInfo->type_id;

                //更新个人作业记录
                $summary[$key]['fastest'] = $this->submitArgs['duration'];

                //更新个人通关最快时间
                $fastestSelf = VipUtils::getFastestSelf($this->submitArgs);
                if (empty($fastestSelf) || $fastestSelf >= $this->submitArgs['duration'])
                    VipUtils::setFastestSelf($this->submitArgs);


                //更新全站通关最快时间
                $fastest = VipUtils::getFastest($this->submitArgs);
                if (empty($fastest) || $fastest >= $this->submitArgs['duration'])
                    VipUtils::setFastest($this->submitArgs);

            }
        }

        $this->submitExerciseRecord['summary'] = json_encode($summary);
    }

    /**
     * 获取自测题目
     *
     * @param array $qids 题目id
     * @param array $userAnswers
     * @return null
     */
    protected function getSelfTestQuestions($qids, &$userAnswers) {
        return parent::getSelfTestQuestions($qids, $userAnswers);
    }

    /**
     * 设置作业的难度等级
     */
    protected function setSummary() {

        $exerciseInfo = $this->exerciseInfo;
        $className    = getClassName($exerciseInfo->calss_id);
        $courseName   = getCourseName($exerciseInfo->course_id);

        $historyExercise = VipUtils::getHistoryUserPrimaryExerciseInfo($this->exerciseId,$this->userId);
        $data = json_decode($historyExercise->summary,true);

        $level = !empty($exerciseInfo->summary) ? $exerciseInfo->summary : '';

        if (isset($data['level_'.$level]['ranking'])) {
            $ranking = (int)$data['level_' . $level]['ranking'];
        } else {
            $ranking = 0;
        }

        $this->data['level']            = (int)$exerciseInfo->summary;
        $this->data['class_name']       = !empty($className) ? $className : '所有课堂';
        $this->data['course_name']      = !empty($courseName) ? $courseName : '所有课程';
        $this->data['exercise_name']    = $exerciseInfo->name;
        $this->data['fastest']          = VipUtils::getFastest(['type_id' => $exerciseInfo->type_id,'level' => $level,'is_arr' => 2]);
        $this->data['ranking']          = $ranking;
    }
    /**
     * 设置提交作业的响应数据
     */
    protected function setSubmitResponseData() {

        $exerciseInfo = $this->exerciseInfo;
        $className    = getClassName($exerciseInfo->calss_id);
        $courseName   = getCourseName($exerciseInfo->course_id);

        $historyExercise = VipUtils::getHistoryUserPrimaryExerciseInfo($this->exerciseId,$this->userId);
        $data = json_decode($historyExercise->summary,true);

        $level = !empty($exerciseInfo->summary) ? $exerciseInfo->summary : '';

        if (isset($data['level_'.$level]['ranking'])) {
            $ranking = (int)$data['level_' . $level]['ranking'];
        } else {
            $ranking = 0;
        }

        $this->submitResponse = [
            'class_name'         => !empty($className) ? $className : '所有课堂',
            'course_name'        => !empty($courseName) ? $courseName : '所有课程',
            'exercise_name'      => $exerciseInfo->name,
            'fastest'            => (int)VipUtils::getFastest(['type_id' => $exerciseInfo->type_id,'level' => $level,'is_arr' => 2]),
            'ranking'            => $ranking
        ];
    }

    /**
     * 通关时间--全站\个人
     *
     * @param $args
     * @return array
     */
    protected function getFastestData($args) {

        $args['is_arr'] = 1;

        $fastest     = VipUtils::getFastest($args);
        $fastestSelf = VipUtils::getFastestSelf($args);

        $result = [];
        foreach ($fastest as $k => $v) {
            $result['level_'.$k] = [
                'fastest'       => $v,
                'fastest_self'  => !empty($fastestSelf[$k]) ? $fastestSelf[$k] : null
            ];
        }
        return $result;
    }

    /**
     * 题号速算自测题目信息
     *
     * @param array $args
     * @return null
     */
    public function submitSelfTest($args) {

        $args['is_arr'] = 1;

        $fastest     = VipUtils::getFastest($args);
        $fastestSelf = VipUtils::getFastestSelf($args);

        if ($args['right'] == $args['total'] && !empty($args['level'])) {

            //更新个人通关最快时间
            if (empty($fastestSelf[$args['level']]) || $fastestSelf[$args['level']] >= $args['duration']) {
                $fastestSelf[$args['level']] = $args['duration'];
                VipUtils::setFastestSelf($args);
            }

            //更新全站通关最快时间
            if (empty($fastest[$args['level']]) || $fastest[$args['level']] >= $args['duration']) {
                $fastest[$args['level']] = $args['duration'];
                VipUtils::setFastest($args);
            }
        }

        $result = [];
        foreach ($fastest as $k => $v) {
            $result['level_'.$k] = [
                'fastest'       => $v,
                'fastest_self'  => !empty($fastestSelf[$k]) ? $fastestSelf[$k] : null
            ];
        }
        return ['data' => $result];
    }

}